<?php

namespace App\Http\Controllers;

use App\Http\Requests\SchoolUseCreater;
use App\Http\Requests\SchoolUserUpdate;
use App\Models\SchoolUser;
use App\Services\UserService;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Gate;

class SchoolUserController extends BaseController
{
    use ValidatesRequests;

    public function list(Request $request)
    {

        $school_id = $request->school_id;
        $campus_id = $request->campus_id;
        $limit = $request->limit;
        $query = SchoolUser::where("school_id", $school_id);

        if (Gate::check("checkSchoolAdmin", [$school_id])) {
            $query->whereIn("campus_id", [$campus_id, 0]);
        } else {
            $query->where("campus_id", $campus_id);
        }

        $res = $query->paginate($limit);
        return resSucc(formatPage($res), "学校列表");
    }

    // 创建员工
    public function create(SchoolUseCreater $request)
    {

        $schoolUsers = $request->validated();

        $school_id = $request->school_id;
        $campus_id = $request->campus_id;
        $phone = $request->phone;

        if (UserService::checkSchoolUser($school_id, $campus_id, $phone)) {
            return resFail(null, "老师已经存");
        }

        $user_id = UserService::checkPassport($phone);

        // 创建用户
        if ($user_id == 0) {
            $password = md5("111111");
            $nickname = $request->teacher_name;
            $user_id = UserService::createUser($phone, $password, $nickname);
        }

        $schoolUsers['school_id'] = $school_id;
        $schoolUsers['campus_id'] = $campus_id;
        $schoolUsers['user_id'] = $user_id;

        $res = SchoolUser::create($schoolUsers);

        return resSucc($res, "创建成功");
    }

    // 更新员工
    public function update(SchoolUserUpdate $request)
    {

        $schoolUsers = $request->validated();

        try{
            if($schoolUsers['identity'] == 'school'){
                $schoolUsers['campus_id'] = 0;
            }
            $res = SchoolUser::where('id', $schoolUsers['id'])->update($schoolUsers);
            return resSucc($res, "更新成功");
        } catch (\Exception $e) {
            return resFail($e, "更新失败");
        } catch (\Throwable $e) {
            return resFail($e, "更新失败");
        }
    }
}
